/*
 * Copyright © 2011 Nokia Corporation. All rights reserved.
 * Nokia and Nokia Connecting People are registered trademarks of Nokia Corporation. 
 * Oracle and Java are trademarks or registered trademarks of Oracle and/or its
 * affiliates. Other product and company names mentioned herein may be trademarks
 * or trade names of their respective owners. 
 * See LICENSE.TXT for license information.
 */ 

package com.nokia.example.wordpress.components;

import com.nokia.example.wordpress.networking.Comment;
import com.nokia.example.wordpress.networking.Post;
import com.nokia.example.wordpress.views.ViewMaster;
import com.nokia.example.wordpress.views.Visual;
import java.util.Vector;
import javax.microedition.lcdui.Graphics;
import javax.microedition.lcdui.Image;

/**
 * A drawer class for rendering the rows in the posts list Visual.
 */
public class PostDrawer implements ListDrawer {

    private final int ROW_HEIGHT = 2 * Visual.SMALL_FONT.getHeight() + 2;
    private ViewMaster view;
    private Image postIcon;

    public PostDrawer(ViewMaster view, Image postIcon) {
        this.view = view;
        this.postIcon = postIcon;
    }

    public int itemHeight() {
        return ROW_HEIGHT;
    }

    private Vector getCommentsForPost(Post post) {
        Vector allComments = DataModel.getInstance().getComments();
        Vector coms = new Vector();
        for (int i = 0; i < allComments.size(); i++) {
            Comment comment = (Comment) allComments.elementAt(i);
            if (comment.postId.equals(post.postId)) {
                coms.addElement(comment);
            }
        }
        return coms;
    }

    public void drawItem(Vector data, Graphics g, int itemIndex, int x, int y, int width, int height, boolean focused) {

        view.drawBackground(g, x, y, width, ROW_HEIGHT, focused);

        g.drawImage(postIcon, x, y + ROW_HEIGHT / 2 - postIcon.getHeight() / 2, g.TOP | g.LEFT);
        int textX = x + postIcon.getWidth() + 2;

        g.setColor(Visual.LIST_PRIMARY_COLOR);
        Post p = (Post) data.elementAt(itemIndex);
        g.setFont(Visual.SMALL_BOLD_FONT);
        g.drawString(p.title, textX, y, g.TOP | g.LEFT);
        y += Visual.SMALL_FONT.getHeight();
        g.setColor(Visual.LIST_SECONDARY_COLOR);
        g.setFont(Visual.SMALL_FONT);
        g.drawString(p.date, textX, y, g.TOP | g.LEFT);
        g.setColor(Visual.LIST_TERTIARY_COLOR);
        int numOfComments = getCommentsForPost(p).size();
        if (numOfComments > 0) {
            g.drawString("" + numOfComments, width, y, g.TOP | g.RIGHT);
        }
    }
}
